<?php

namespace App\Models;


use Illuminate\Support\Facades\DB;

class AdminLog extends Base
{

    // [系统] 操作日志
    protected $table = 'admin_log';

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id', 'uid',];

    // 保存系统日志记录
    public function saveLog($uid, $title, $en_title, $url, $ip = '', $remark = '')
    {
        // 系统日志记录
        // uid 操作用户
        // username 操作用户
        // title 操作菜单
        // url  请求地址 $this->request->url()
        // remark '保存数据' : '浏览数据'
        // ip $this->request->ip()
        // param $this->request->param()

        // 组合数据
        //$log['param']  = json_encode($data['param'], JSON_UNESCAPED_UNICODE);
        $log   = ['uid' => $uid, 'title' => $title, 'en_title' => $en_title, 'param' => '[]', 'url' => $url, 'ip' => $ip, 'remark' => $remark, 'date' => date('Ymd'),];
        $where = ['uid' => $uid, 'title' => $title, 'en_title' => $en_title, 'param' => '[]', 'date' => date('Ymd'),];
        Db::beginTransaction();
        try{
            // 查找日志是否存在
            $info = $this->where($where)->lock(true)->first();
            if($info === false){
                throw new \Exception('获取日志失败！', 400);
            }

            // 保存日志或者更新日志
            if(!$info){
                $this->fill($log);
                $return = $this->save();
            } else{
                $log['id']    = $info->id;
                $log['count'] = $info->count + 1;
                // 保存
                $return = $info->save($log);
            }
            if($return === false){
                throw new \Exception('保存日志失败！', 400);
            }

            Db::commit();
        } catch(\Exception $e){
            Db::rollback();

            return $this->return_false($e->getMessage(), $e->getCode());
        }

        return $return;
    }


    // 定义验证操作
    public function rules()
    {

        $add = [];

        $edit = [];

        $info = [];

        $rule = [
            'id'      => 'require|integer',
            'site_id' => 'require|integer',
            'uid'     => 'require|integer',
            'title'   => 'require|max:100',
            'url'     => 'require|max:200',
            'param'   => 'require|max:16777215',
            'remark'  => 'require|max:255',
            'count'   => 'require|integer',
            'ip'      => 'require|max:128',
            'date'    => 'require|integer',
            'ctime'   => 'require|integer',
            'mtime'   => 'require|integer',
        ];

        $msg = [
            'id'     => '自增量',
            'uid'    => '后台操作用户',
            'title'  => '操作目录',
            'url'    => '操作链接',
            'param'  => '链接参数',
            'remark' => '备注',
            'count'  => '操作次数',
            'ip'     => '操作IP',
            'date'   => '日期',
            'ctime'  => '创建时间',
            'mtime'  => '修改时间',
        ];

        return ['rule' => $rule, 'msg' => $msg, 'add' => $add, 'info' => $info];
    }

}


